#!./bin/python
# ----------------------------------------------------------------------
# Create required pools
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------

# Third-party modules
import yaml
# NOC modules
from noc.main.models.pool import Pool
from noc.config import config
from noc.core.mongo.connection import connect

CONFIG = config.path.legacy_config


def update_if_changed(pool, values):
    changed = False
    for k in values:
        if getattr(pool, k) != values[k] and values[k] is not None:
            setattr(pool, k, values[k])
            changed = True
    if changed:
        pool.save()
    return changed


def main():
    with open(CONFIG) as f:
        data = yaml.safe_load(f)
    connect()
    changed = False
    for p in data["pools"]:
        try:
            pool = Pool.objects.get(name=p)
            changed |= update_if_changed(pool, {
                "description": data["pools"][p]["description"],
                "discovery_reschedule_limit": data["pools"][p].get("discovery_reschedule_limit")
            })
        except Pool.DoesNotExist:
            Pool(
                name=p,
                description=data["pools"][p]["description"]
            ).save()
            changed = True
    if changed:
        print("CHANGED")
    else:
        print("OK")


if __name__ == "__main__":
    main()
